<template>
  <div class="flex flex-col h-full">
    <ReadCard ref="readCardRef" business-type="住院结算" module-type="住院" :call-back-data="patientData" @read="getPatientInfoByID" @tab-change="tabChange">
      <template #selfCost>
        <!-- <a-card> -->
        <a-form ref="formRef" :model="formState" class="flex justify-between">
          <div class="flex">
            <a-form-item name="brName" class="w-[260px] mr-3 !mb-0">
              <SelectTable
                v-model:value="formState.brName"
                :search-params="{}"
                type="住院结算待结算患者列表"
                placeholder="姓名/助记码/卡号/手机号/身份证号"
                @select="onSelect"
              />
            </a-form-item>
          </div>
          <div>
            <a-button type="primary" @click="handleSearch">刷新</a-button>
          </div>
        </a-form>
        <!-- </a-card> -->
      </template>
      <template v-if="tabActiveKey !== '自费'" #rightBtn>
        <div class="w-[280px] flex items-center justify-end shrink-0">
          <span class="mr-2 font-bold">医保结算</span>
          <a-switch v-model:checked="formState.settlementType" class="mr-4" />
          <a-button class="mx-2" disabled @click="onClickReset(true)">重置</a-button>
          <a-button type="primary" @click="handleSearch">刷新</a-button>
        </div>
      </template>
    </ReadCard>
    <PatientInfoHeader :patient-info="patientData" class="mt-2" @change="getPatientInfo(patientData.inplsh)">
      <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
      <div>
        <div class="flex items-center">
          <LabelValue label="住院号" :value="patientData.admissionCode" :width="180" label-class="w-[67px] text-right" />
          <LabelValue label="住院科室" :value="patientData.ksmc" :width="180" />
          <LabelValue label="住院病区" :value="patientData.wardName" :width="160" />
          <LabelValue label="床位号" :value="patientData.lastBedCode" :width="160" />
          <LabelValue label="入院日期" :value="patientData.admissionTime" :width="200" />
        </div>
        <div class="flex items-center">
          <LabelValue label="住院天数" :value="formatDay(patientData.zyts)" :width="180" />
          <LabelValue label="账户余额" :value="formatMoney(patientData.ye)" :width="180" />
          <LabelValue label="押金金额" :value="formatMoney(patientData.yjje)" :width="320" />
          <LabelValue label="出院日期" :value="patientData.dischargeDate" :width="200" />
        </div>
      </div>
    </PatientInfoHeader>
    <div class="mt-2 flex flex-1 overflow-hidden">
      <div class="w-3/5 mr-2 relative overflow-auto">
        <a-card>
          <div class="flex justify-between items-center mb-2">
            <BaseTitle title="收费明细" />
            <template v-if="tabActiveKey !== '自费' && formState.settlementType">
              <BaseButton type="primary" class="mr-2" :disabled="!patientData.inplsh" ghost comfirm-text="确认处方撤销？" @click="onRxUploadCancel()">
                处方撤销
              </BaseButton>
              <BaseButton type="primary" comfirm-text="确认处方上传？" :disabled="!patientData.inplsh" ghost class="mr-2" @click="onRxUpload()">
                处方上传
              </BaseButton>
            </template>
            <a-button type="primary" :disabled="!tableDataDetail.length" @click="onClickDiscounts(1)"> 批量打折 </a-button>
          </div>
          <BaseTable :loading="loading" column-code="000198" :scroll="{ x: 1000 }" :height="getLeftTableHeight()" :data-source="tableDataDetail" bordered>
            <template #bodyCell="{ column, index, record }">
              <template v-if="column.dataIndex === 'xh'">
                {{ index + 1 }}
              </template>
              <template v-if="column.dataIndex === 'advName'">
                <MedicineInfo :value="{ mc: record?.advName, gg: record?.spc, cj: record?.cj }" />
              </template>
              <template v-if="column.dataIndex === 'yzzt'">
                <a-tag v-if="!+record.yzzt" color="green">正常</a-tag>
                <a-tag v-else color="red">失效</a-tag>
              </template>
              <template v-if="column.dataIndex === 'action'">
                <a-button type="link" size="small" @click="onClickDiscounts(record)"> 打折 </a-button>
              </template>
            </template>
          </BaseTable>
        </a-card>
        <div class="absolute w-full">
          <div v-if="showPrescription" class="overflow-auto overflow-x-hidden" style="max-height: 340px">
            <a-card v-for="(item, index) in prescriptionList" :key="index" class="mt-2 pb-4">
              <div class="flex mb-2">
                <BaseTitle class="!w-[150px] !mb-0" :title="'中药处方' + (index + 1) + '-加工'" />
                <div class="flex items-center">
                  <a-select v-model:value="item.drugStoreId" class="w-64" placeholder="请选择" :options="drugRoomList" />
                  <a-radio-group v-model:value="item.jzfs" class="ml-5" @change="onChangeRadio(item)">
                    <a-radio value="自煎">自煎</a-radio>
                    <a-radio value="代煎">代煎</a-radio>
                  </a-radio-group>
                </div>
              </div>
              <div class="w-full">
                <div class="flex mb-2">
                  <div class="font-bold mx-2 w-9 flex items-center">加工</div>
                  <div v-if="item.jzfs === '代煎'" class="order-footer w-full" @click="onClickProcessOpen(item, 1)">
                    {{ generateProcess(item, item?.processMethod) }}
                  </div>
                  <div v-else class="w-full color-placeholder">自煎无加工</div>
                </div>
                <div class="flex">
                  <div class="font-bold mx-2 w-9 flex items-center">快递</div>
                  <div class="order-footer w-full" @click="onClickProcessOpen(item, 2)">
                    {{ generateExpress(item.express) }}
                  </div>
                  <a-button type="text" danger size="small" @click="onclickDelete(item)">删除</a-button>
                </div>
              </div>
            </a-card>
          </div>
        </div>
      </div>

      <div class="w-2/5 flex flex-col overflow-auto">
        <a-card class="w-full">
          <BaseTitle title="收费类别" class="!mb-2.5" />
          <BaseTable :loading="loading" column-code="000199" :data-source="tableDataType" bordered :height="getRightTableHeight()">
            <template #bodyCell="{ column, index }">
              <template v-if="column.dataIndex === 'xh'">
                {{ index + 1 }}
              </template>
            </template>
            <template #footer>
              <div class="flex items-center justify-end text-right w-full px-4">
                <div v-if="tabActiveKey !== '自费'" class="flex items-center mr-12">
                  未贯标金额：<span class="text-xl font-bold">￥{{ formatAmount(wgbje) }}</span>
                </div>
                医疗费：<span class="text-xl font-bold text-red-500">￥{{ formatAmount(medicalPrice) }}</span>
              </div>
            </template>
          </BaseTable>
        </a-card>
        <div class="flex flex-col relative w-full flex-1">
          <a-card v-if="tabActiveKey !== '自费'" class="mt-2">
            <BaseTitle title="医保结算" class="!mb-0">
              <div class="flex">
                <span class="mr-1 font-normal">医保账户支付</span>
                <a-switch v-model:checked="isUseCHS" class="mr-6" />
                <a-button type="primary" size="small" :disabled="!formState.brName" @click="onPreSettlement()">预结算</a-button>
              </div>
            </BaseTitle>
            <div class="flex justify-between flex-wrap mt-4">
              <div class="w-1/2 mb-2">
                <span class="inline-block w-32 text-right">医疗总金额: </span>
                <span class="text-base">￥{{ formatAmount(preSettlementInfo.outPocketAmountResponse?.ysje || 0) }}</span>
              </div>
              <div class="w-1/2 mb-2">
                <span class="inline-block w-32 text-right">账户余额: </span>
                <span class="text-base">￥{{ formatAmount(preSettlementInfo.outPocketAmountResponse?.zhye || 0) }}</span>
              </div>
              <div class="w-1/2 flex items-center">
                <span class="inline-block w-32 text-right">医保支付: </span>
                <span class="text-base">￥{{ formatAmount(preSettlementInfo.outPocketAmountResponse?.ybzf || 0) }}</span>
                <a-popover trigger="click">
                  <template #content> <CHSPopover :data="preSettlementInfo.medicareAmountResponse" /> </template>
                  <a-button size="small" class="ml-2" shape="circle">
                    <span class="text-sm">?</span>
                  </a-button>
                </a-popover>
              </div>
              <div class="w-1/2">
                <span class="inline-block w-32 text-right">未贯标金额: </span>
                <span class="text-base">￥{{ formatAmount(preSettlementInfo.outPocketAmountResponse?.wgbje || 0) }}</span>
              </div>
            </div>
          </a-card>
          <a-card class="mt-2 w-full h-full border-t relative" :body-style="{ height: '100%' }">
            <div class="text-right mr-2 mb-2 absolute bottom-0 right-0">
              <div class="my-2">
                本次实收 <span class="text-3xl text-red-500 font-bold">￥{{ formatAmount(medicalPrice) }}</span>
              </div>
              <!-- chargeStatus 0 未结账 1 已结账 2 退费中 3 已挂账-->
              <BaseButton v-if="patientData.chargeStatus === 0" confirm-text="是否确认该病人挂账出院?" type="primary" size="large" ghost @click="onCredit()"
                >挂账</BaseButton
              >
              <a-button v-if="patientData.inplsh && patientData.isNmiYbdj === 0" type="primary" size="large" class="ml-2" ghost @click="openMedicalModal"
                >医保登记</a-button
              >
              <BaseButton
                v-if="patientData.inplsh && patientData.isNmiYbdj === 1"
                confirm-text="确认撤销医保登记?"
                type="primary"
                class="ml-2"
                size="large"
                @click="openMedicalModal"
              >
                撤销医保登记
              </BaseButton>
              <template v-if="tabActiveKey !== '自费'">
                <a-button v-if="patientData.cydjzt === 1" class="ml-2 w-32" size="large" type="primary" ghost @click="onOutHospitalCancel">
                  撤销出院登记
                </a-button>
                <a-button v-else class="ml-2 w-28" size="large" type="primary" ghost @click="outHospitalOpen = true">出院登记</a-button>
              </template>
              <a-button class="ml-2 w-28" size="large" type="primary" ghost @click="printInList">住院清单</a-button>
              <a-button
                v-if="patientData.chargeStatus === 0 || patientData.chargeStatus === 3"
                type="primary"
                class="ml-2 w-28"
                size="large"
                :loading="chargeLoading"
                :disabled="!formState.brName"
                @click="onClickCharge"
              >
                收费
              </a-button>
              <BaseButton
                v-if="patientData.chargeStatus === 1"
                confirm-text="确认取消结算?"
                type="primary"
                class="ml-2 w-28"
                size="large"
                :disabled="!formState.brName"
                @click="onCancelCharge"
              >
                取消结算
              </BaseButton>
            </div>
          </a-card>
        </div>
      </div>
    </div>
    <!-- 医保登记 -->
    <MedicalRegistration
      v-model:open="medicalOpen"
      :patient-info="{ ...patientData, bedCode: patientData.lastBedCode }"
      :select-name-disabled="true"
      :deposit-type="0"
      @success="onEditSuccess"
    />
    <!-- 出院登记 -->
    <OutHospitalRegister v-model:open="outHospitalOpen" :inplsh="patientData.inplsh" />
    <!-- 收费弹窗 -->
    <ChargeModal
      v-model:open="chargeOpen"
      :br-id="patientData.brId"
      :business-data="{ ysje: medicalPrice, ...preSettlementInfo }"
      :charge-title="chargeTitle"
      source-type="1"
      is-dispose
      :inplsh="patientData.inplsh"
      @success="onChargeSuccess"
    />
    <!-- 退费弹窗 -->
    <RefundModal v-model:open="refundOpen" :register-price="medicalPrice" :charge-data="chargeTitle" @success="onSuccessPrice" />
    <!-- 医保收费 -->
    <!-- <InsuranceModal v-model:open="CHSChargeOpen" :register-price="medicalPrice" :charge-data="chargeData" @success="onSuccessPriceCHS" /> -->
    <ModalExpress v-model:open="expressOpen" :row-data="orderData.express" @ok="onProcessOk" />
    <ModalProcess v-model:open="processOpen" :row-data="orderData.processMethod" @ok="onProcessOk" />
    <DiscountsOne v-model:open="discountsOneOpen" :row-data="projectRow" @success="onDiscountsSuccess" />
    <DiscountsMany v-model:open="discountsManyOpen" :discounts-data="tableDataDetail" @success="onDiscountsSuccess" />
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import BaseTitle from '@/components/BaseTitle'
import SelectTable from '@/components/SelectTable'
import { formatAmount } from '@/utils/format.js'
import { post } from '@/utils/request'
import BaseTable from '@/components/BaseTable'
import ModalExpress from '@/components/ModalExpress'
import ModalProcess from '@/components/ModalProcess'
import { getSystemConfig } from '@/utils/systemConfig'
import ChargeModal from '@/components/ChargeModal'
import RefundModal from '@/components/ChargeModal/return'
import MedicalRegistration from '../components/MedicalRegistration.vue'
// import InsuranceModal from '@/components/ChargeModal/InsuranceModal'

// import PreferentialCard from '../components/PreferentialCard'
// import useUserStore from '@/store/user'
// import CouponCard from '@/components/CouponCard'
import DiscountsOne from './components/DiscountsOne'
import DiscountsMany from './components/DiscountsMany'
import OutHospitalRegister from './components/OutHospitalRegister'

const route = useRoute()
const router = useRouter()
// const { empId } = useUserStore()
const loading = ref(false)
const chargeOpen = ref(false)
const refundOpen = ref(false)

const tabActiveKey = ref('自费') //选中的
const showPrescription = ref(false)
const processOpen = ref(false)
const expressOpen = ref(false)
const discountsOneOpen = ref(false)
const discountsManyOpen = ref(false)
const isCoupon = ref(true)
const tableDataType = ref([])
const tableDataDetail = ref([])
const patientData = ref({})
const tableDetailId = ref([])
const drugRoomList = ref([])
const prescriptionList = ref([])
const projectRow = ref({})
const orderData = ref({})
const formState = ref({
  settlementType: true
})
const zydzIds = ref([])
const formRef = ref(null)
const differenceAmount = ref(0)
const wgbje = ref(0) //未贯标金额
const medicalPrice = ref(0) // 应收金额
const depositPrice = ref(0) // 押金金额
const couponId = ref(null)
const readCardRef = ref(null)
const getLeftTableHeight = () => {
  const topHeight = 300
  if (prescriptionList.value.length === 0) {
    return window.innerHeight - topHeight
  }
  if (prescriptionList.value.length === 1) {
    return window.innerHeight - topHeight - 154
  }
  if (prescriptionList.value.length > 1) {
    return window.innerHeight - topHeight - 308
  }
}
const getRightTableHeight = () => {
  const CHSHeight = tabActiveKey.value !== '自费' ? 45 : 0
  const topHeight = 300
  const tableHeight = window.innerHeight - topHeight - 580 - CHSHeight
  return tableHeight < 240 ? 240 : tableHeight
}
const onSelect = async (select) => {
  formState.value.brName = select.brName
  patientData.value = select
  patientData.value.inplsh = select.inplsh
  depositPrice.value = select.yjje
}

// 单项
const onClickDiscounts = async (row) => {
  if (row === 1) {
    discountsManyOpen.value = true
  } else {
    projectRow.value = { ...row }
    discountsOneOpen.value = true
  }
}
//获取收费明细和收费类别数据
const chargeDetailList = async () => {
  loading.value = true
  const { code, data = [], msg } = await post('/inp/inpComprehensive/getUnpaidPatientBillList', { inplsh: patientData.value.inplsh, jslb: 'SF' })
  if (code !== 0) return message.error(msg)
  tableDataDetail.value = data.patientBillList
  tableDetailId.value = data.patientBillList.map((item) => item.id)
  tableDataType.value = data.patientBillTypeList
  loading.value = false
  medicalPrice.value = data.amountStr
  wgbje.value = data.wgbje
  zydzIds.value = data.zydzId
  // getReceiptsAmount()
  // getReceiptsCount()
}
//判断是否有中药费
// const getReceiptsCount = async () => {
//   showPrescription.value = tableDataDetail.value.some((item) => item.advTypeName === '中药费')
//   await getPrescription()
// }
// const getPrescription = async () => {
//   const { data, code, msg } = await post('/outp/outpClinicalOrder/getOutpTCMHeadList', { jzbh: [jzbh.value], jksy: 1 })
//   if (code !== 0) return message.error(msg)
//   prescriptionList.value = data
//   getReceiptsAmount()
// }
const onChangeRadio = async (row) => {
  orderData.value = row
  if (row.jzfs === '自煎') {
    row.processMethod = { processMethodCost: 0 }
  } else {
    row.processMethod = orderData.value.processMethod
  }
  await onSaveMedicineList()
}

const generateProcess = (row, processMethod = {}) => {
  if (Object.keys(processMethod).length > 1) {
    return `${processMethod?.processMethodName || ''} ${processMethod?.processMethodCmemo || ''}`
  }
  if (row.jzfs === '自煎' && Object.keys(processMethod).length === 1) {
    return '暂无加工'
  }
  if (row.jzfs === '代煎' && Object.keys(processMethod).length === 1) {
    return '点击填写'
  }
}
const generateExpress = (express = {}) => {
  if (Object.keys(express).length > 0) {
    return `${express.sjr || '收件人'}，${express.sjrtel || '电话'}，${express.province || ''}${express.city || ''}${express.county || ''}${
      express.patientAddressId || ''
    } ${express.expressMode || ''} ${express.expressCmemo || ''}`
  }
  if (Object.keys(express).length === 0) {
    return '点击填写'
  }
}
const onClickProcessOpen = (row, state) => {
  orderData.value = row
  if (row.jzfs === '代煎' && state === 1) {
    processOpen.value = true
  }
  if (state === 2) {
    expressOpen.value = true
  }
}
const onProcessOk = async (row) => {
  if (row.processMethodName) {
    orderData.value.processMethod = row
  } else {
    orderData.value.express = row
  }
  const findState = prescriptionList.value.findIndex((x) => x.drugStoreId === orderData.value.drugStoreId)
  if (findState !== -1) {
    prescriptionList.value.splice(findState, 1, orderData.value)
  }
  await onSaveMedicineList()
}

const onDiscountsSuccess = async (params) => {
  const { code, msg } = await post('/inp/inpComprehensive/doDiscountBill', { ...params, inplsh: patientData.value.inplsh })
  if (code !== 0) return message.error(msg)
  discountsOneOpen.value = false
  message.success(msg)
  getPatientInfo(patientData.value.inplsh)
  chargeDetailList()
}

const onclickDelete = async (row) => {
  row.express = {}
  await onSaveMedicineList()
}
const onSaveMedicineList = () => {
  prescriptionList.value.forEach(async (item) => {
    const params = {
      ...item
    }
    const { code, msg } = await post('/outp/outpClinicalOrder/doSaveOutpTCMHead', params)
    if (code !== 0) return message.error(msg || '操作失败')
  })
}

const onSuccessPrice = async (params = {}) => {
  const { code, msg } = await post('/inp/inpComprehensive/doSavePatientBill', {
    ...params,
    ypzje: medicalPrice.value,
    tfje: medicalPrice.value,
    fbyh: differenceAmount.value,
    yjzf: patientData.value.yjje,
    brId: patientData.value.brId,
    inplsh: patientData.value.inplsh || 0,
    patientCouponsId: couponId.value ? couponId.value : undefined,
    ids: zydzIds.value
  })
  if (code !== 0) return message.error(msg)
  message.success(msg)
  chargeTitle.value = ''
  chargeOpen.value = false
  refundOpen.value = false
  onPrint()
  if (getSystemConfig('INP_CHARGE_AUTO_PRINT_EXPENSE_DOCUMENT' === '1')) await onPrintInventory()
  onClickReset()
  // chargeDetailList()
  // router.push({
  //   path: '/in-registration/workstation'
  // })
}

// 住院结算单据
const onPrint = async () => {
  const { code, msg, data } = await post('/inp/Print/printSettlementDocumentsList', {
    inplsh: patientData.value.inplsh
  })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}
//住院清单
const onPrintInventory = async () => {
  const { code, msg, data } = await post('/inp/Print/printAdmissionList', {
    inplsh: patientData.value.inplsh,
    jslb: 'SF',
    dylb: 'ZY'
  })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}
// 医保报销单
const onPrintMedical = async () => {
  const { code, msg, data } = await post('/inp/Print/printFeeStatements', {
    inplsh: patientData.value.inplsh
  })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}
const handleSearch = () => {
  if (!formState.value.brName) return
  chargeDetailList()
}

const chargeTitle = ref('')
const chargeLoading = ref(false)
const onClickCharge = async () => {
  chargeLoading.value = true
  const res = await post('/inp/inpComprehensive/getInpExpensesStatus', { inplsh: patientData.value.inplsh })
  chargeLoading.value = false
  if (res.code !== 0) return message.error(res.msg || '收费失败')
  if (tabActiveKey.value === '自费' || !formState.value.settlementType) {
    //实收金额为0时，不弹收费/退费弹窗
    if (Number(formatAmount(medicalPrice.value)) === 0) {
      const { code, data } = await post('/outp/oupCharge/getChargeTypeList')
      if (code !== 0) return
      const formObj = {}
      data.forEach((item) => {
        formObj[item.zffsdm] = 0
      })
      formObj.ssje = 0
      onSuccessPrice(formObj)
    } else if (Number(formatAmount(medicalPrice.value)) >= 0) {
      // 收费弹窗
      chargeOpen.value = true
      chargeTitle.value = `账户余额￥${patientData.value.ye} | 累计押金￥${patientData.value.yjje}   住院费用￥${medicalPrice.value}`
    } else {
      // 退费弹窗
      refundOpen.value = true
      chargeTitle.value = `账户余额￥${patientData.value.ye} | 累计押金￥${patientData.value.yjje}   住院费用￥${medicalPrice.value}`
    }
  } else {
    //CHS医保收费
    onPreSettlement(true)
  }
}
//取消结算
const onCancelCharge = async () => {
  const { code, msg } = await post('/inp/inpComprehensive/doSaveReverseSettlement', { inplsh: patientData.value.inplsh }, { loading: true })
  if (code !== 0) return message.error(msg)
  message.success(msg || '操作成功')
  onClickReset()
}
//挂账
const onCredit = async () => {
  const { code, msg } = await post(
    '/inp/inpComprehensive/doSaveReverseSettlement',
    { inplsh: patientData.value.inplsh, creditAmount: medicalPrice.value, isGz: '1' },
    { loading: true }
  )
  if (code !== 0) return message.error(msg)
  message.success(msg || '操作成功')
  onClickReset()
}
const getPatientInfo = async (lsh) => {
  const { code, msg, data } = await post('/inp/inpComprehensive/getUnpaidPatientList', {
    inplsh: lsh
  })
  if (code !== 0) return message.error(msg)
  if (data && data.length > 0) {
    formState.value.brName = data[0].brName
    patientData.value = data[0]
    depositPrice.value = data[0].yjje
  } else {
    message.error('患者查询为空')
    router.push({
      path: '/in-registration/workstation'
    })
  }
}
const onClickReset = (flag) => {
  preSettlementInfo.value = {}
  formState.value.brName = ''
  formState.value.settlementType = true
  patientData.value = {}
  chargeTitle.value = ''
  tableDataDetail.value = []
  prescriptionList.value = []
  tableDataType.value = []
  zydzIds.value = []
  differenceAmount.value = 0
  medicalPrice.value = 0
  wgbje.value = 0
  chargeOpen.value = false
  refundOpen.value = false
  isUseCHS.value = true
  readCardRef.value?.reset()
  if (route.query.lsh && flag) {
    getPatientInfo(route.query.lsh)
  }
}

const printInList = async () => {
  const { code, msg, data } = await post('/inp/Print/printAdmissionList', {
    inplsh: patientData.value.inplsh,
    jslb: 'SF'
  })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}
const formatDay = (value) => {
  if (value === undefined || value === null) {
    return '-'
  } else {
    return value + ' 天'
  }
}
const formatMoney = (value) => {
  return formatAmount(value) + ' 元'
}
watch(
  () => patientData.value.inplsh,
  (val) => {
    if (val) chargeDetailList()
    // getDrugRooms()
  }
)

onMounted(() => {
  if (route.query.lsh) {
    getPatientInfo(route.query.lsh)
  }
  isCoupon.value = getSystemConfig('ENABLE_REGISTER_DISCOUNT') === '1' //启用挂号优惠功能
})
// 医保相关修改---------------------------------
const outHospitalOpen = ref(false)
const isUseCHS = ref(true)
const readCardInfo = ref({})
// const jsonStr = ref('')
// const readSuccess = async (res) => {
//   // jsonStr.value = str
//   // if (!window.openExe) {
//   //   jsonStr.value =
//   //     '{"ybkRquese":{"cardtype":"1","carddata":""},"ybkResonse":{"xb":"女","sfzh":"310104195701174561","lxdh":"65537984","txdz":"淮海中路1799号","yzbm":"200233","klbbz":"1","kh":"D06073096","xm":"张美芳","zhbz":"2000000000000000","dnzhye":0.0,"lnzhye":0.0,"mzzfdxjzfljs":300.0,"zyzfxxzfljs":1200.0,"mzzfdde":300.0,"zyzfdde":1200.0,"tczffdxde":610000.0,"qfxsfdxxfylj":24274.97,"jlch":"100806419510","mzylbkdd":"","br_id":"0100014351","xzqh":"","ybsqjmbz":"1"}}'
//   // } //获取医保信息
//   // const res = await post('/nationalMedicalInsurance/nmiCommon/getPatientlnfo', {
//   //   jsonStr: jsonStr.value,
//   //   mdtrtCertNo: '',
//   //   mdtrtCertType: '03'
//   // })
//   // if (res.code !== 0) return message.error(res.msg || '获取医保信息失败')
// }
const tabChange = (val) => {
  tabActiveKey.value = val
  onClickReset(true)
}
const getPatientInfoByID = async (res) => {
  readCardInfo.value = res
  const { code, msg, data } = await post('/inp/inpComprehensive/getUnpaidPatientList', {
    brId: readCardInfo.value.ybkResonse.br_id
  })
  if (code !== 0) return message.error(msg)
  if (data && data.length > 0) {
    formState.value.brName = data[0].brName
    patientData.value = data[0]
    depositPrice.value = data[0].yjje
  } else {
    message.error('患者查询为空')
  }
}
// //上传处方
// const onUploadCase = async () => {
//   if (!patientData.value.inplsh) return message.error('请先选择患者')
//   callWindow()
//   const { msg, code } = await post('/inp/inpComprehensive/doUploadNMlOrderltemList', {
//     acct_used_flag: isUseCHS.value ? '1' : '0',
//     ids: zydzIds.value,
//     inplsh: patientData.value.inplsh,
//     psn_No: readCardInfo.value.psn_no
//   })
//   if (code !== 0) return message.error(msg)
//   message.success('上传成功')
// }

const onChargeSuccess = async (chargeData = {}) => {
  //阜阳医保才会调壳验证密码
  let verRes = ''
  if (getSystemConfig('NMI_REGION_CODE') === '022' && patientData.value.insutype === '310' && tabActiveKey.value === '社保卡') {
    verRes = await window.openExe?.iVerifyPIN()
  }
  const { code, msg } = await post(
    '/inp/inpComprehensive/doHospitalizationSettlement',
    {
      ...chargeData,
      // ypzje: medicalPrice.value,
      tfje: medicalPrice.value > 0 ? 0 : -medicalPrice.value,
      // fbyh: differenceAmount.value,
      // yjzf: patientData.value.yjje,
      // brId: patientData.value.brId,
      // patientCouponsId: couponId.value ? couponId.value : undefined,
      ids: zydzIds.value,
      inplsh: patientData.value.inplsh || 0,
      pjhm: preSettlementInfo.value?.outPocketAmountResponse?.pjhm,
      //医保相关属性
      acct_used_flag: isUseCHS.value ? '1' : '0',
      insureStatus: tabActiveKey.value !== '自费' && formState.value.settlementType ? 1 : 0,
      ...preSettlementInfo.value?.medicareAmountResponse,
      ...readCardInfo.value,
      ...readCardInfo.value.baseinfo,
      mmJson: verRes ? verRes : undefined
    },
    { loading: true }
  )
  if (code !== 0) return message.error(msg)
  message.success(msg)
  await onPrint()
  if (getSystemConfig('INP_CHARGE_AUTO_PRINT_EXPENSE_DOCUMENT' === '1')) await onPrintInventory()
  if (tabActiveKey.value !== '自费' && formState.value.settlementType) {
    // 医保报销单打印
    await onPrintMedical()
  }
  setTimeout(() => {
    chargeOpen.value = false
    patientData.value = {}
    onClickReset()
  }, 100)
}

const preSettlementInfo = ref({}) //预结算数据
// 预结算
const onPreSettlement = async (isOpen = false) => {
  const res = await post(
    '/inp/inpComprehensive/doHospitalizationPreSettlement',
    {
      acct_used_flag: isUseCHS.value ? '1' : '0',
      inplsh: patientData.value.inplsh,
      ...readCardInfo.value.baseinfo,
      ...readCardInfo.value,
      jzpzbh_1101: readCardInfo.value.mdtrt_cert_no,
      mdtrtCertNo: readCardInfo.value.mdtrt_cert_no
    },
    { loading: true }
  )
  if (res.code !== 0) return message.error(res.msg)
  preSettlementInfo.value = res.data || {}
  chargeOpen.value = isOpen
}
// 上传处方
const onRxUpload = async () => {
  const res = await post(
    '/inp/inpComprehensive/doPrescriptionUpload',
    {
      acct_used_flag: isUseCHS.value ? '1' : '0',
      inplsh: patientData.value.inplsh,
      ...readCardInfo.value.baseinfo,
      ...readCardInfo.value
    },
    { loading: true }
  )
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.msg || '处方上传成功')
}
// 处方撤销
const onRxUploadCancel = async () => {
  const res = await post(
    '/inp/inpComprehensive/doFeeReversal',
    {
      inplsh: patientData.value.inplsh
    },
    { loading: true }
  )
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.msg || '撤销成功')
}
// 登记撤销
const onOutHospitalCancel = async () => {
  const res = await post(
    '/inp/inpComprehensive/doHospitalizationRevokedS',
    {
      inplsh: patientData.value.inplsh,
      ybkh: readCardInfo.value.kh
    },
    { loading: true }
  )
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.msg || '撤销成功')
}
const medicalOpen = ref(false)
const openMedicalModal = () => {
  medicalOpen.value = true
}
const onEditSuccess = () => {
  getPatientInfo(patientData.value.inplsh)
}
</script>
<style lang="less" scoped>
.order-footer {
  @apply cursor-pointer border-b py-1;
}
:deep(.ant-tabs-content-holder) {
  overflow: hidden;
}
.discount-input {
  :deep(.ant-input) {
    text-align: right;
  }
}
.color-placeholder {
  color: var(--disabled-text-color);
}
</style>
